package com.whh.controller;

import com.whh.pojo.ResultVO;
import com.whh.pojo.UserInfo;
import com.whh.service.UserService;
import com.whh.util.Constants;
import com.whh.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserInfoController {

    @Autowired
    @Qualifier("UserServiceImpl")
    private UserService userService;

    //登录
    @RequestMapping("/toLogin")
    public String toLogin()
    {
        return "login";
    }

    @RequestMapping("/login")
    public String login(String userName, String password ,  Model model,HttpSession session){
        UserInfo userInfo = userService.queryByNameUser(userName);
        if (userInfo==null&& !MD5Utils.createMD5(password).equals(userInfo.getPassword())){//查有此人登录
            model.addAttribute("msg","用户名或者密码错误请重新登录");
            //没有查询到用户则返回到登录页面
            return "login";
        }
        //把用户信息存储到常量工具类中用于对用户进行拦截以及判断用户等级
        session.setAttribute(Constants.USERName_SESSION,userName);
        session.setAttribute(Constants.USER_SESSION,userInfo);
        //登录成功欢迎该用户
        model.addAttribute("msg", "欢迎你尊敬的"
                +session.getAttribute(Constants.USERName_SESSION)+"会员");
        //重定向到下载上传文件页面
        return "redirect:/file/allFile";

    }

    //注册
    @RequestMapping("/toregister")
    public String toRegister(){
        return "register";
    }
    @RequestMapping("/register")
    public String registerController(UserInfo user){
        if (userService.registerUser(user)>0){
            return "redirect:/user/toLogin";
        }
        return "redirect:/user/toregister";
    }

    //判断注册用户名是否有效
    @RequestMapping("/check")
    @ResponseBody
    public ResultVO checkUserName(String userName){
        System.out.println(userName);

        UserInfo userInfo = userService.queryByNameUser(userName);
        ResultVO resultVO=new ResultVO();
        if (userInfo!=null){
            resultVO.setFlag(true);
            resultVO.setMessage("用户名已存在");
        }else
        {
            resultVO.setFlag(false);
            resultVO.setMessage("用户名可用");
        }
        return resultVO;
    }
}
